//
//  KlViewController.swift
//  yihuiwang_mac
//
//  Created by 张衡 on 2020/9/7.
//  Copyright © 2020 1meeting. All rights reserved.
//

import Foundation


class KlViewController: NSViewController {
    
    var navBlock:os_block_t?
    var stitle: String?
    var massageText:String?
    var buttomTitles:[String] = []
    var subbuttoms:[NSButton] = []
    var indexBlock:((Int,KlViewController)->())?
    var isDismiss:Bool = true
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, 400, 130))
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(237).cgColor
        self.view = view
    }
    
    convenience init(title:String?,
                     massage:String?,
                     buttomTitles:[String],
                     indexBlock:((Int,KlViewController)->())?,
                     navBlock:os_block_t?) {
        self.init()
        self.stitle = title
        self.massageText = massage
        self.indexBlock = indexBlock
        self.navBlock = navBlock
        self.buttomTitles = buttomTitles
        self.setupUI()
        self.loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func loadData() {
        let heigit = self.massageText?.ga_height(font: self.message.font!.pointSize, width: self.view.frame.size.width-40) ?? 0
        self.view.window?.setContentSize(NSSize.init(width: self.view.frame.size.width, height: heigit+80+60))
        self.message.stringValue = self.massageText!
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        self.refactoringWindow()
    }
    
    
    func refactoringWindow() {
        self.view.window?.standardWindowButton(.zoomButton)?.isHidden = true
        self.view.window?.standardWindowButton(.miniaturizeButton)?.isHidden = true
        self.view.window?.standardWindowButton(.closeButton)?.isHidden = true
        self.view.window?.styleMask = [.titled,.closable]
        self.view.window?.collectionBehavior = NSWindow.CollectionBehavior.fullScreenPrimary
        
        let closeBtn = self.view.window?.standardWindowButton(NSWindow.ButtonType.closeButton)
        closeBtn?.target = self
        closeBtn?.action = #selector(navCloseBtnAction)
    }
    
    func setupUI() {
        
        self.view.addSubview(buttomView)
        buttomView.snp.makeConstraints { (make) in
            make.bottom.centerX.width.equalToSuperview()
            make.height.equalTo(50)
        }
        self.subbuttoms = self.initButtoms(inView: self.buttomView, titles: self.buttomTitles)
        
        self.view.addSubview(iconImage)
        iconImage.snp.makeConstraints { (make) in
            make.width.height.equalTo(64)
            make.top.equalTo(20)
            make.left.equalTo(20)
        }
        
        if let t = self.stitle {
            self.title = t
        }
        
        let max_width = self.view.frame.width - 64 - 40
        if let msg = self.massageText {
            self.view.addSubview(message)
            let fontSize = self.stitle == nil ? self.message.font!.pointSize+2:self.message.font!.pointSize
            let fontColor = self.stitle == nil ? color_gray(0):color_gray(80)
            message.stringValue = msg
            message.font = NSFont.systemFont(ofSize: CGFloat(fontSize))
            message.textColor = fontColor
            message.snp.makeConstraints { (make) in
                make.left.equalTo(iconImage.snp.right).offset(10)
                make.width.equalTo(max_width)
                make.top.equalTo(iconImage).offset(5)
            }
        }
        
        self.view.addSubview(indicator)
        indicator.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-10)
        }
        
    }
    
    func startLoading() {
        self.indicator.isHidden = false
        self.message.isHidden = true
        self.indicator.startAnimation(nil)
        subbuttoms.forEach { (buttom) in
            buttom.isEnabled = false
        }
        
    }
    
    func stopLoading() {
        self.indicator.stopAnimation(nil)
        subbuttoms.forEach { (buttom) in
            buttom.isEnabled = true
        }
        self.indicator.isHidden = true
        self.message.isHidden = false
    }
    
    lazy var buttomView: NSView = {
        let view = NSView.init()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_rgba(r: 245, g: 245, b: 245, a: 0).cgColor
        return view
    }()
    
    lazy var iconImage: NSImageView = {
        let imageV = NSImageView.init(image: NSImage.image(name: "AppIcon") ?? NSImage.init())
        return imageV
    }()
    
    lazy var message: NSLabel = {
        let lab = NSLabel.label(title: "....", textColor: color_gray(80), font: NSFont.boldSystemFont(ofSize: 14))
        lab.maximumNumberOfLines = 5
        lab.alignment = .left
        lab.sizeToFit()
        return lab
    }()
    
    lazy var indicator: NSProgressIndicator = {
        let view = NSProgressIndicator.init(frame: NSRect.zero)
        view.style = .spinning
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.clear.cgColor
        view.controlSize = .regular
        view.isHidden = true
        view.sizeToFit()
        return view
    }()
    
    func initButtoms(inView:NSView,titles:[String]) -> [NSButton] {
        var subbuttoms:[NSButton] = []
        for (index,value) in titles.enumerated() {
            let btn = NSButton.init()
            btn.bezelStyle = .rounded
            btn.title = value
            btn.font = NSFont.systemFont(ofSize: 12)
            if index == 0 {
                btn.becomeFirstResponder()
                btn.keyEquivalent = "\r"
            }
            btn.tag = index
            btn.target = self
            btn.action = #selector(subbuttomsAction(senber:))
            inView.addSubview(btn)
            subbuttoms.append(btn)
            btn.snp.makeConstraints { (make) in
                let width = btn.ga_width(font:btn.font!.pointSize)+20
                let fwidth = width < 80 ? 80:width
                make.width.equalTo(fwidth)
                make.centerY.equalToSuperview()
                if index == 0 {
                    make.right.equalTo(-20)
                }else {
                    make.right.equalTo(subbuttoms[index-1].snp.left).offset(-10)
                }
                
            }
        }
        return subbuttoms
    }
    
    func kl_dismiss(_ sender: Any?) {
        self.view.window?.orderOut(sender)
        self.view.window?.close()
    }
    
    @objc func subbuttomsAction(senber:NSButton) {
        if let block = self.indexBlock {
            if self.isDismiss {
                self.kl_dismiss(nil)
            }
            block(senber.tag,self)
        }
    }
    
    @objc func navCloseBtnAction() {
        self.view.window?.orderOut(nil)
        if let block = self.navBlock {
            block()
        }
    }
}
